package com.haoran.dwz.web;

import java.math.BigDecimal;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.PostConstruct;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.haoran.dwz.common.redis.RedisSequenceWorker;
import com.haoran.dwz.common.security.UsmContextHolder;
import com.haoran.dwz.common.swagger2.Swagger2Facade;
import com.haoran.dwz.common.util.AddressUtil;
import com.haoran.dwz.domain.entities.Menu;
import com.haoran.dwz.domain.entities.User;
import com.haoran.dwz.service.ApiLogService;
import com.haoran.dwz.service.MenuService;
import com.haoran.dwz.service.PersonalizationService;
import com.haoran.dwz.service.ShortUrlService;

import io.swagger.models.Swagger;
import springfox.documentation.annotations.ApiIgnore;


@Controller
@ConfigurationProperties(prefix="cors")
@ApiIgnore
public class IndexController {
	private Logger logger = LoggerFactory.getLogger(getClass());
	private String upgradeTime;
	@PostConstruct
	private void init(){
		upgradeTime =  DateFormatUtils.format(new Date(), "yyyy年MM月dd日 HH:mm");
	}
	
	@Autowired
	private ShortUrlService shortUrlService;
	
	@Autowired
	private ApiLogService apiLogService;
	
	@Value("${cors.pathPattern}")
	private String pathPattern;
	
	
	@Value("${cors.allowedOrigins}")
	private String allowedOrigins;

	@Value("${cors.allowedMethods}")
	private String allowedMethods;
	
	@Value("${cors.maxAge}")
	private long maxAge; 
	
	@Value("${cors.allowCredentials}")
	private boolean allowCredentials; 

	@Value("${swagger.title}")
	private String title;
	

	@Value("${system.version:1.0.0}")
	private String version;
	
	@Autowired
	private RedisSequenceWorker redisSequenceWorker;
	
	@Autowired
	private Swagger2Facade swagger2Facade;
	
	@Autowired
	private MenuService menuService;
	
	@Autowired
	private PersonalizationService personalizationService;
	
	@RequestMapping({"/","index"})
	public String index(Model model) {
		User user = UsmContextHolder.getUser();
		model.addAttribute("admin", user);
		String hostAddress = AddressUtil.getHostAddress();
		logger.info("hostAddress={}",hostAddress);
		model.addAttribute("apiTitle", title);
		model.addAttribute("version", version);
		model.addAttribute("upgradeTime", upgradeTime);
		String userId = UsmContextHolder.getUserId();
		String personalization = personalizationService.getPersonalization(userId, "theme");
		if(StringUtils.isBlank(personalization)) {
			personalization = "index-c";
			personalizationService.setPersonalization(userId, "theme", personalization);
		} 
		Collection<Menu> menuList = menuService.findAllByRole(user.getDefaultRole());
		model.addAttribute("menus",menuList);
		return personalization;
	}
	
	@RequestMapping(value = "toggle/{theme}" , method = {RequestMethod.GET})
	public String dispacherIndex(@PathVariable("theme")String theme , Model model) {
		String userId = UsmContextHolder.getUserId();
		String index = "index-"+theme;
		personalizationService.setPersonalization(userId, "theme", index);
		return "redirect:/index";
	}
	
    @RequestMapping(value = "main", method = {RequestMethod.GET})
    public String home(Model model) {
        model.addAllAttributes(this.getTotal());
        return "main";
    }
    
    @RequestMapping(value = "login", method = {RequestMethod.GET})
    public String login() {
        return "login";
    }
    
    private Map<String, Object> getTotal() {
        Map<String, Object> model = new HashMap<String, Object>();
     	Swagger documentation = swagger2Facade.getDocumentation(null);
        model.put("tagsCount", documentation.getTags().size());
        model.put("apiCount", documentation.getPaths().size());
      	model.put("pathPattern", pathPattern);
    	model.put("allowedOrigins", allowedOrigins);
    	model.put("allowedMethods", allowedMethods);
    	model.put("maxAge", maxAge);
    	model.put("allowCredentials", allowCredentials);
    	BigDecimal[] successRate = apiLogService.successRate();
    	model.put("callTotal", successRate[0].toString());
		model.put("successRate", successRate[1].toString());
		model.put("totalRate", redisSequenceWorker.currentUsedRate().toString());
    	model.put("countDWZ", shortUrlService.count());
        return model;
    }

}
